#ifndef __HX711_H
#define __HX711_H

#include "ebox_core.h"
#include "filters.h"
#include "preferences.h"
#include "ripple.h"

class HX711 
{
    public:
        typedef enum{HighSpeed,LowSpeed}Speed_t;
    public:
        HX711(Gpio *sck, Gpio *dout);
        void begin(Speed_t speed = LowSpeed);
        void set(Speed_t speed);
        void loop();
        float get_raw();
    
        Ripple *rpl;
    
    private:
        Gpio *_sck;
        Gpio *_dout; 
    
        uint32_t last,rate_last;
        FilterMoveWindow *filter;
    
        uint32_t read();
        float raw;
    
        uint16_t rate_count;
        uint16_t rate;

};

#include "linear.h"
class Balance : public HX711
{
    public:
        Balance(Gpio *sck, Gpio *dout);
        void begin();
        void add_row(double y);
        int calibration_add(double y,float rpl_max, int times);
        void calibration_clear();
        int calibration();
        void peel(float w = 0);
        void peel_no_save(float w = 0);
        float get_peel(){return _peel;};
        double get_rate(){return _rate;};
        double get_offset(){return _offset;};
        int   get_rpl_threshold(){return rpl->get_threshold();};

        void set_rpl_threshold(int v){rpl->set_threshold(v);     prefs->putInt("rpl_th",v);}; 
    
    
        float get_weight_no_peel();
        double get_weight();
        double get_weight_0000();
        int   get_weight_asInt();
        float get_weight_as_x10g();
        float get_weight_accuracy_10g();
        float get_weight_peel();
    
        double get_r(){return R;}
        double get_r_last(){return RNew;}
        int get_rows(){return linear->get_rows();};
    private:
        Linear *linear;
        Preferences *prefs;

        double _rate;
        double _offset;
        float _peel;
        void set_offset(double v){_offset = v;prefs->putDouble("offset",v);};
        void set_rate(double v){ _rate = v;   prefs->putDouble("rate",v);};
        void set_peel(float v){_peel = v;     prefs->putFloat("peel",v);}; 
        
        double R;
        double RNew;
};

#endif
